import cv2
import numpy as np
from utils.common import load_image, show_image, make_dirs  # 导入公共函数
from utils.config import exp3_Sobel_path, exp3_output_dir  # 导入输出路径

# 确保输出目录存在
make_dirs(exp3_output_dir)

# 加载图片并显示
image = load_image()
show_image("Original Image", image)

# 灰度化
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
show_image("Grayscale Image", gray_image)


# Sobel边缘检测
# 计算水平和垂直梯度
sobel_x = cv2.Sobel(gray_image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(gray_image, cv2.CV_64F, 0, 1, ksize=3)
# 计算边缘强度
sobel = np.sqrt(sobel_x**2 + sobel_y**2).astype(np.uint8)
cv2.imshow("Sobel X", np.abs(sobel_x).astype(np.uint8))
cv2.imshow("Sobel Y", np.abs(sobel_y).astype(np.uint8))
cv2.imshow("Sobel Combined", sobel)
# 保存结果
cv2.imwrite(exp3_Sobel_path, gray_image)
print(f"灰度化结果已保存到：{exp3_Sobel_path}")